import type { ResumeData } from '../types';

function fillInput(element: HTMLInputElement | HTMLTextAreaElement | null, value: string) {
  if (!element) return;
  element.value = value;
  element.dispatchEvent(new Event('input', { bubbles: true }));
  element.dispatchEvent(new Event('change', { bubbles: true }));
}

export const zhiyeAdapter = {
  matcher: (url: URL) => url.hostname.includes('zhiye.com'),

  filler: (resumeData: ResumeData) => {
    console.log('[Debug] 智业适配器填充器 V2 (修复版) 已启动。');
    
    const mapping = {
      '姓名': resumeData.basicInfo.name,
      '手机': resumeData.basicInfo.phone,
      '邮箱': resumeData.basicInfo.email,
      '毕业院校': resumeData.education.school,
      '专业': resumeData.education.major,
      '学位': resumeData.education.degree,
    };

    document.querySelectorAll('label.form-item__text').forEach(label => {
      const labelElement = label as HTMLElement;
      const labelText = labelElement.innerText.trim();

      if (mapping[labelText as keyof typeof mapping]) {
        console.log(`[Debug] 命中关键词: "${labelText}"`);
        const value = mapping[labelText as keyof typeof mapping];
        
        // 【核心修复】: 采用更健壮的父子查找法
        const formItemDiv = labelElement.closest('.form-item'); // 1. 找到共同的父元素
        if (formItemDiv) {
          console.log(`[Debug] -> 成功找到共同父元素 .form-item`, formItemDiv);
          const controlDiv = formItemDiv.querySelector('.form-item__control'); // 2. 在父元素内找 control div
          if (controlDiv) {
            console.log(`[Debug] --> 成功找到 controlDiv`, controlDiv);
            const inputElement = controlDiv.querySelector('input, textarea'); // 3. 在 control div 内找 input
            if (inputElement) {
              console.log(`[Debug] ---> 成功找到输入框，准备填写: "${value}"`, inputElement);
              fillInput(inputElement as HTMLInputElement | HTMLTextAreaElement, value);
            } else {
              console.warn(`[Debug] ---> 警告: 在 .form-item__control 中未找到输入框!`);
            }
          } else {
            console.warn(`[Debug] --> 警告: 在 .form-item 中未找到 .form-item__control!`);
          }
        } else {
          console.warn(`[Debug] -> 警告: 未找到 "${labelText}" 标签的 .form-item 父元素!`);
        }
      }
    });

    alert('智业招聘适配器(修复版)填写完成！请检查效果。');
  },
};